package com.anysoft.user.bankcard;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.BaseBean;
import com.anysoft.bean.QueryBankInfoListBean;
import com.anysoft.bean.QueryProvinceCityBean;
import com.anysoft.bean.QuickAuthApplyBean;
import com.anysoft.bean.SmartCardBinByBankAccountNoBean;
import com.anysoft.event.RegisterEvent;
import com.anysoft.linstener.OnNextLinstener;
import com.anysoft.me.callback.StringDialogCallback;
import com.anysoft.me.config.ServiceConfig;
import com.anysoft.me.utils.PermissionManager;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.ChinaPayUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.StringUtils;
import com.anysoft.utils.image.MD5Encoder;
import com.anysoft.view.picker.NomarlPickerPopupWindow;
import com.anysoft.web.MerChantsBankActivity;
import com.google.gson.Gson;
import com.hxcr.chinapay.activity.Initialize;
import com.hxcr.chinapay.util.CPGlobaInfo;
import com.hxcr.chinapay.util.Utils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 添加银行卡界面 wyb 2017-02-15
 */
public class AddBankCardActivity extends BaseActivity implements PermissionManager.OnPermissionListener {
    private final static int EDIT_MOBILE = 104;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.leftButton)
    Button leftButton;

    @BindView(R.id.et_bank_card_no_val)
    EditText et_bank_card_no_val;//银行卡号
    @BindView(R.id.tv_bank_reserve_phone_val)
    TextView tv_bank_reserve_phone_val;//预留手机号
    @BindView(R.id.image_select_bank)
    ImageView image_select_bank;//选择银行卡
    @BindView(R.id.tv_bank_card_name_val)
    TextView tv_bank_card_name_val;//归属银行名称
    @BindView(R.id.et_verification_code_val)
    EditText et_verification_code_val;//短信验证码
    @BindView(R.id.btn_get_verification_code)
    Button btn_get_verification_code;//获取短信验证码
    @BindView(R.id.btn_next)
    Button btn_next;//下一步
    @BindView(R.id.rl_select_province_city)
    RelativeLayout rl_select_province_city;//
    @BindView(R.id.tv_province_city_name)
    TextView tv_province_city_name;//省市名称

    @BindView(R.id.rl_select_region_county)
    RelativeLayout rl_select_region_county;//
    @BindView(R.id.tv_region_county_name)
    TextView tv_region_county_name;//市区名称

    @BindView(R.id.tv_bank_reserve_phone_edit)
    TextView tv_bank_reserve_phone_edit;//更改电话号码

    @BindView(R.id.tv_add_bank_card_tip)
    TextView tv_add_bank_card_tip;//温馨提示

    @BindView(R.id.iv_add_bank_card_ocr)
    ImageView iv_add_bank_card_ocr;//添加银行卡


    /**
     * 支持开户的银行
     */
//    private List<QueryBankInfoListBean.DataBean> bankList;
    /**
     * 所选择银行在列表中的索引
     */
    private int iSelectBankIndex;
    /**
     * 所选择银行编号
     */
    private String bankCode;//
    private String trustChannelId;//


    private TimeCount time;
    /**
     * 是否在获取验证码中（60秒倒计时中）
     */
    private boolean getVerificationing = false;


    /**
     * 3：省 4：市
     */
    private int currentType = 1;
    private int currentPosition;
    private String selectedProvince = "";
    private String provinceCode;//所选择的省代码
    private String cityCode;//所选择的市代码
    private NomarlPickerPopupWindow nomarlPickerPopupWindow;
    private boolean provincePopShow = false;
    private boolean cityPopShow = false;
    private boolean bankPopShow = false;
    private boolean isSelectedProvinceChanged = false;
    private List<QueryProvinceCityBean.DataBean> provinceList = new ArrayList<>();
    private List<QueryProvinceCityBean.DataBean> cityList = new ArrayList<>();
    private List<QueryBankInfoListBean.DataBean> bankList = new ArrayList<>();//支持开户的银行(包括可定投的)
    private List<QueryBankInfoListBean.DataBean> bankListAndChannel = new ArrayList<>();//支持可定投的银行
    private ArrayList<String> list = new ArrayList<>();
    private int selectPosition = -1;
    /**
     * 鉴权申请返回数据
     */
    private QuickAuthApplyBean.DataBean currentDataBean;

    private String currLoginFundCustomerNo = "";
    private String addType;//银行卡添加类型 planBuy：添加可定投的一行卡   否则为正常
    private String planBuyFundNo;//所要绑定的  银行卡的基金编号
    private String shareClass;//所要绑定的  银行卡的交易类型
    private String bankName;
    private boolean isScanBankResult = false;
    private String bank_card_no_val;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_bank_card);
        ButterKnife.bind(this);
        title.setText("添加银行卡");
        time = new TimeCount(120000, 1000);
        addType = getIntent().getStringExtra("addType");
        planBuyFundNo = getIntent().getStringExtra("planByFundNo");
        shareClass = getIntent().getStringExtra("shareClass");
        currLoginFundCustomerNo = getFundCustomerNo();
        tv_bank_reserve_phone_val.setText(mentorApplication.accountLoginBean.getData().getMobileNo());
        et_bank_card_no_val.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (StringUtils.isNullOrEmpty(et_bank_card_no_val.getText().toString())) {
                        return;
                    }
                    queryCardBinByBankAccountNo();
                } else {
                    isScanBankResult = false;
                }
            }
        });
        setOnNextLinstener(new OnNextLinstener() {
            @Override
            public void OnCancelNext() {
                doVerificationCodeCheck();
                isScanBankResult = false;
            }

            @Override
            public void OnConfirmNext() {
                et_bank_card_no_val.clearFocus();
            }

            @Override
            public void OndoConfirm() {

            }
        });
        getBankList();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EDIT_MOBILE://获取用户最新手机号进行显示
                    tv_bank_reserve_phone_val.setText(data.getStringExtra("mobile") + "");
                    break;
            }
        } else if (requestCode == HostConstant.START_BANK_CARD && resultCode == HostConstant.RESULT_BANK_CARD) {
            isScanBankResult = true;
            bank_card_no_val = data.getStringExtra("CardNum").replace(" ", "");
            et_bank_card_no_val.setText(bank_card_no_val);
            queryCardBinByBankAccountNo();
        } else if (requestCode == HostConstant.START_CHANTS_BANK && resultCode == HostConstant.RESULT_CHANTS_BANK) {
            String status = data.getStringExtra("status");
            if ("Y".equals(status)) {
                addBankCardUpLoad();
            }
        }
    }

    @OnClick({R.id.leftButton, R.id.rl_select_bank, R.id.btn_get_verification_code, R.id.rl_select_province_city,
            R.id.rl_select_region_county, R.id.tv_bank_reserve_phone_edit, R.id.btn_next, R.id.tv_add_bank_card_tip
            , R.id.iv_add_bank_card_ocr})
    public void onClick(View view) {
        if (!isFastDoubleClick()) {
            collapseSoftInputMethod(view.getWindowToken());
            if (et_bank_card_no_val.hasFocus() && !StringUtils.isNullOrEmpty(et_bank_card_no_val.getText().toString())) {
                et_verification_code_val.requestFocus();
                queryCardBinByBankAccountNo();
            }
            switch (view.getId()) {
                case R.id.iv_add_bank_card_ocr:
                    requestIdentityPermissions();
                    break;
                case R.id.leftButton:
                    finish();
                    break;
                case R.id.rl_select_bank:
                    bankPopShow = true;
                    currentType = 2;
                    currentPosition = 0;

                    initPopList();
                    if (list != null && !list.isEmpty() && list.size() > 0) {
                        showPicker();
                    } else {
                        getBankList();
                    }
                    break;
                case R.id.btn_get_verification_code: //验证码

                    if (!dataCheck(1)) {
                        return;
                    }
                    if (isScanBankResult) {
                        showConfirmAlert(this, "提示", "请核对扫描结果,如有误请手动输入。\n\n银行卡名称:" + bankName + "\n银行卡号: " + bank_card_no_val,
                                "有误,去修改", "无误,继续");
                    } else {
                        doVerificationCodeCheck();
                    }
                    break;
                case R.id.rl_select_province_city: //省市选择
                    currentType = 3;

                    provincePopShow = true;
                    currentPosition = 0;

                    initPopList();

                    if (list != null && !list.isEmpty() && list.size() > 0) {
                        showPicker();
                    } else {
                        getProvinceCity(0, "");
                    }
                    break;
                case R.id.rl_select_region_county: //市区选择
                    if (TextUtils.isEmpty(selectedProvince)) {
//                        showToast("请先选择您所在的省");
                        showConfirmAlert(mActivity, "请选择省市");
                        return;
                    }
                    currentType = 4;

                    cityPopShow = true;
                    currentPosition = 0;

                    if (isSelectedProvinceChanged) {
                        cityList.clear();
                        isSelectedProvinceChanged = false;
                    }

                    initPopList();

                    if (list != null && !list.isEmpty() && list.size() > 0) {
                        showPicker();
                    } else {
                        getProvinceCity(1, selectedProvince);
                    }

                    break;
                case R.id.tv_bank_reserve_phone_edit:
                    Intent intent = new Intent(AddBankCardActivity.this, EditMobileActivity.class);
                    startActivityForResult(intent, EDIT_MOBILE);
                    break;
                case R.id.tv_add_bank_card_tip:
                    selectWarmPromptByType("3");
                    break;
                case R.id.btn_next: //下一步
                    if (!dataCheck(2)) {
                        return;
                    }

                    if (bankList == null) {
//                        showToast("请选择归属银行！");
                        showConfirmAlert(mActivity, "请选择银行卡");
                        return;
                    }

                    if (!TextUtils.isEmpty(currentDataBean.getMerId())) {
                        //银联渠道
                        UpdateChinaPayAuth(currentDataBean);
                    } else {
                        quickAuthConfirm(saveAddBankCardEvent.getAuthApplyNo());
                    }
                    break;
            }
        }
    }

    private void requestIdentityPermissions() {
        if (PermissionManager.getInstance().checkPermissions(this, PermissionManager.PERMISSION_READ_WEITE_CAMERA)) {
            ActivityUtils.openBankCardCamera(this);
        } else {
            PermissionManager.getInstance().requestPermissions(this, PermissionManager.REQUEST_READ_WEITE_CAMERA,
                    PermissionManager.PERMISSION_READ_WEITE_CAMERA, this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionSuccess() {
        ActivityUtils.openBankCardCamera(this);
    }

    @Override
    public void onPermissionFail() {
        ToastUtils.showShort("请求权限失败,请重试");
    }

    private void doVerificationCodeCheck() {
        if (Pattern.matches(MentorConst.REGEX_MOBILE, tv_bank_reserve_phone_val.getText().toString())) {
            sMobileNo = "";
            quickAuthApply();
        } else {
            showConfirmAlert(mActivity, "手机号格式不对");
        }
    }

    /**
     * 增开银行卡
     */
    private void addBankCardUpLoad() {
        Map<String, String> params = new HashMap<>();
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());//基金公司客户号
        params.put("token", mentorApplication.userBean.getToken());//
        params.put("authApplyNo", "" + saveAddBankCardEvent.getAuthApplyNo());//原鉴权申请单号
        params.put("bankCode", "" + saveAddBankCardEvent.getBankCode());//银行编号
        params.put("bankAccountNo", "" + saveAddBankCardEvent.getBankAccountNo());//银行账号
        params.put("trustChannelId", "" + saveAddBankCardEvent.getTrustChannelId());//交易渠道
        params.put("provinceCode", "" + provinceCode);//省代码
        params.put("cityCode", "" + cityCode);//市代码
        params.put("userName", "" + saveAddBankCardEvent.getUsername());//真实姓名
        params.put("mobilePhone", "" + saveAddBankCardEvent.getMobilePhone());//手机号

        Logger.t("-----ADD_BANK_CARD-----").d(HttpUtils.createRequestUrl(this, HostConstant.ADD_BANK_CARD, params));
        String requestJson = new Gson().toJson(HttpUtils.getCommonParams(this, params));
        try {
            requestJson = MD5Encoder.encode(requestJson);
            requestJson = requestJson.toUpperCase();
            params.put("applicationNo", "" + requestJson);//
        } catch (Exception e) {
            e.printStackTrace();
        }

        OkGo.<String>post(HostConstant.ADD_BANK_CARD)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "添加银行卡：", response.body());
                        parseJson_save(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast(MentorConst.INTERNET_ERROR);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析重置密码接口返回的数据
     *
     * @param response
     */
    private void parseJson_save(String response) {
        BaseBean bean;
        try {
            bean = new Gson().fromJson(response, BaseBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            return;
        }
        showToast("银行卡添加成功！");
        setResult(RESULT_OK);
        finish();
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
            btn_get_verification_code.setClickable(false);
            btn_get_verification_code.setText(millisUntilFinished / 1000 + "秒后重发");
            getVerificationing = true;
        }

        @Override
        public void onFinish() {
            btn_get_verification_code.setText("获取验证码");
            btn_get_verification_code.setClickable(true);
            btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_click_style);
            getVerificationing = false;

        }
    }


    /**
     * 获取支持开卡的数据集合
     */
    private void getBankList() {
        if ("planBuy".equals(addType)) {
            queryFundBuyPlanChannel();
        } else {
            queryBankListInfo();
        }
    }

    /**
     * 查询普通可添加的银行卡列表
     */
    private void queryBankListInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());//
        params.put("OpenAccountState", "0");
        OkGo.<String>post(HostConstant.QUERY_BANK_INFO_LIST)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "查询开户支持的银行:", response.body());
                        UpdateBankList(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 更新银行卡列表数据
     *
     * @param json
     */
    private void UpdateBankList(String json) {
        bankList.clear();

        QueryBankInfoListBean bean;
        try {
            bean = new Gson().fromJson(json, QueryBankInfoListBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }
//
        if (bean == null || bean.getData() == null ||
                bean.getData().isEmpty() || bean.getData().size() < 1) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }
        list.clear();
        bankList.clear();
        bankList.addAll(bean.getData());

        initPopList();

        if (bankPopShow) {
            showPicker();
        }

    }

    /**
     * 查询可定投的银行卡
     */
    private void queryFundBuyPlanChannel() {

        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());
        params.put("fundCode", planBuyFundNo);//fundCode
        params.put("shareClass", shareClass);//shareClass
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());//fundCustomerNo
        OkGo.<String>post(HostConstant.QUERY_PLAN_BANK_INFO_LIST)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJsonFundBuyPlanChannel(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析可定投银行卡数据
     *
     * @param json
     */
    private void parseJsonFundBuyPlanChannel(String json) {
        QueryBankInfoListBean bean;
        try {
            bean = new Gson().fromJson(json, QueryBankInfoListBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }
//
        if (bean == null || bean.getData() == null ||
                bean.getData().isEmpty() || bean.getData().size() < 1) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_plan_data));
            return;
        }

        list.clear();
        bankList.clear();
        bankList.addAll(bean.getData());

        initPopList();

        if (bankPopShow) {
            showPicker();
        }

    }
    ///////////////////省市逻辑

    /**
     * @param queryType    0-省，1-市
     * @param provinceCode 查市时必传
     */
    private void getProvinceCity(final int queryType, String provinceCode) {
        Map<String, String> params = new HashMap<>();
        params.put("queryType", queryType + "");
        if (queryType == 1) {
            params.put("provinceCode", provinceCode);
        }
        OkGo.<String>post(HostConstant.QUERY_PROVINCE_CITY)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateProvinceCity(response.body(), queryType);
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void UpdateProvinceCity(String json, int queryType) {

        QueryProvinceCityBean bean;
        try {
            bean = new Gson().fromJson(json, QueryProvinceCityBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null ||
                bean.getData().isEmpty() || bean.getData().size() < 1) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        list.clear();

        switch (queryType) {
            case 0: //省/市
                provinceList.clear();
                provinceList.addAll(bean.getData());

                initPopList();

                if (provincePopShow) {
                    showPicker();
                }
                break;
            case 1: //市/区
                cityList.clear();
                cityList.addAll(bean.getData());

                initPopList();

                if (cityPopShow) {
                    showPicker();
                }
                break;
            default:
                break;
        }
    }

    private void initPopList() {
        list.clear();

        switch (currentType) {
            case 2://银行卡
                for (QueryBankInfoListBean.DataBean dataBean : bankList) {
                    list.add(dataBean.getBankName());
                }
                break;
            case 3: //省市选择
                for (QueryProvinceCityBean.DataBean dataBean : provinceList) {
                    list.add(dataBean.getProvinceName());
                }
                break;
            case 4: //市区选择
                for (QueryProvinceCityBean.DataBean dataBean : cityList) {
                    list.add(dataBean.getCityName());
                }
                break;
            default:
                break;
        }

    }

    private void showPicker() {
        nomarlPickerPopupWindow = new NomarlPickerPopupWindow(mActivity, itemsOnClick, list);
        nomarlPickerPopupWindow.showAtLocation(findViewById(R.id.activity_add_bank_card),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        switch (currentType) {
            case 2:
                nomarlPickerPopupWindow.setTitle_str("请选择银行卡");
                break;
            case 3:
                nomarlPickerPopupWindow.setTitle_str("请选择省市");
                break;
            case 4:
                nomarlPickerPopupWindow.setTitle_str("请选择城市");
                break;
            default:
                break;
        }

        nomarlPickerPopupWindow.setOnPickerChangeListener(
                new NomarlPickerPopupWindow.OnPickerChangeListener() {
                    @Override
                    public void onPickerChange(int position) {
                        currentPosition = position;
                    }
                });

    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            nomarlPickerPopupWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_cancel:
                    if (nomarlPickerPopupWindow != null) {
                        nomarlPickerPopupWindow.dismiss();
                    }
                    break;
                case R.id.btn_sure:
                    if (nomarlPickerPopupWindow != null) {
                        selectPosition = currentPosition;
                        nomarlPickerPopupWindow.dismiss();

                        switch (currentType) {
                            case 2:
                                bankName = bankList.get(selectPosition).getBankName();
                                tv_bank_card_name_val.setText(bankName);
                                bankCode = bankList.get(selectPosition).getBankCode();
                                trustChannelId = bankList.get(selectPosition).getTrustChannelId();
                                saveAddBankCardEvent.setTrustChannelId(trustChannelId);
                                isScanBankResult = false;
                                break;
                            case 3:
                                tv_province_city_name.setText(list.get(selectPosition));
                                if (selectedProvince != provinceList.get(selectPosition).getProvinceCode()) {
                                    isSelectedProvinceChanged = true;
                                    tv_region_county_name.setText("");
                                    cityCode = "";
                                }
                                selectedProvince = provinceList.get(selectPosition).getProvinceCode();
                                provinceCode = provinceList.get(selectPosition).getProvinceCode();
                                break;
                            case 4:
                                tv_region_county_name.setText(list.get(selectPosition));
                                cityCode = cityList.get(selectPosition).getCityCode();
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 数据校验
     *
     * @param checkType 1：鉴权 2：绑定银行卡
     * @return
     */
    private boolean dataCheck(int checkType) {

        //银行卡号
        bank_card_no_val = et_bank_card_no_val.getText().toString().trim();
        String verification_code_val = et_verification_code_val.getText().toString().trim();//短信验证码
        String bank_reserve_phone_val = tv_bank_reserve_phone_val.getText().toString().trim();//手机号
        if (StringUtils.isNullOrEmpty(bank_card_no_val)) {
//            showToast("请输入银行卡号!");
            showConfirmAlert(mActivity, "请输入银行卡卡号");
            return false;
        }
        if (StringUtils.isNullOrEmpty(bankCode)) {
//            showToast("请选择归属银行!");
            showConfirmAlert(mActivity, "请选择银行卡");
            return false;
        }
        if (checkType == 2) {
            if (StringUtils.isNullOrEmpty(provinceCode)) {
//                showToast("选择省/市!");
                showConfirmAlert(mActivity, "请选择省市");
                return false;
            }
            if (StringUtils.isNullOrEmpty(cityCode)) {
//                showToast("选择市/区!");
                showConfirmAlert(mActivity, "请选择城市");
                return false;
            }
            if (StringUtils.isNullOrEmpty(verification_code_val)) {
//                showToast("请填写短信验证码!");
                showConfirmAlert(mActivity, "请输入短信验证码");
                return false;
            }
            if (StringUtils.isNullOrEmpty(sMobileNo)) {
//                showToast("请获取短信验证码!");
                showConfirmAlert(mActivity, "请先获取短信验证码");
                return false;
            }
        }
        if (StringUtils.isNullOrEmpty(bank_reserve_phone_val)) {
//            showToast("手机号不能为空!");
            showConfirmAlert(mActivity, "手机号不能为空");
            return false;
        }
        return true;
    }

    ///////////////////////鉴权
    private String sMobileNo;
    //    /**
//     * 鉴权申请号
//     */
//    private String authApplyNo;
    private RegisterEvent saveAddBankCardEvent = new RegisterEvent();

    /**
     * 鉴权接口
     */
    private void quickAuthApply() {
        Map<String, String> params = new HashMap<>();
        bank_card_no_val = et_bank_card_no_val.getText().toString().trim();//银行卡号
        String bank_reserve_phone = tv_bank_reserve_phone_val.getText().toString().trim();//预留手机号

        if (bankList == null) {
            showConfirmAlert(mActivity, "请选择归属银行");
            return;
        }
        params.put("bankCode", bankCode);//银行代码
        params.put("bankName", bankName);//银行名称
        params.put("bankAccountNo", bank_card_no_val);//银行账号
        params.put("username", mentorApplication.userBean.getUserName());//投资人姓名
        params.put("identityType", mentorApplication.accountLoginBean.getData().getIdentityType());//证件类型
        params.put("identityNo", mentorApplication.accountLoginBean.getData().getIdentityNo());//证件号码
        params.put("mobilePhone", bank_reserve_phone);//手机号码
        params.put("authType", "0");//鉴权类型		M	0-开户鉴权，1-找回密码鉴权
        params.put("trustChannelId", "" + trustChannelId);//交易渠道
        params.put("operationType", "2");//0-开户 1-忘记密码  2-加卡

        saveAddBankCardEvent = new RegisterEvent();
        saveAddBankCardEvent.setBankCode(bankCode);
        saveAddBankCardEvent.setBankAccountNo(bank_card_no_val);
        saveAddBankCardEvent.setUsername(mentorApplication.userBean.getUserName());
        saveAddBankCardEvent.setMobilePhone(bank_reserve_phone);
        saveAddBankCardEvent.setIdentityType(mentorApplication.accountLoginBean.getData().getIdentityType());
        saveAddBankCardEvent.setIdentityNo(mentorApplication.accountLoginBean.getData().getIdentityNo());

        setVerificationCodeStatuts(false);
        OkGo.<String>post(HostConstant.QUICK_AUTH_APPLY)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "鉴权申请(开户第一步):", response.body());
                        parseJson_QuickAuth(1, response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        setVerificationCodeStatuts(true);
                        showToast("验证码获取失败！");
                        sMobileNo = "";
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 鉴权确认
     *
     * @param authApplyNo
     */
    private void quickAuthConfirm(String authApplyNo) {

        if (!saveAddBankCardEvent.getBankAccountNo().equals(et_bank_card_no_val.getText().toString().trim()) ||
                !saveAddBankCardEvent.getBankCode().equals(bankCode) ||
                !saveAddBankCardEvent.getMobilePhone().equals(tv_bank_reserve_phone_val.getText().toString().trim())
                ) {

            showConfirmAlert(mActivity, "您修改了信息，请重新获取验证码");
//                    authApplyNo = "";
            return;
        }

        Map<String, String> params = new HashMap<>();

        if (checkParam(params, "authApplyNo", authApplyNo, "鉴权失败！")) {
            return;
        }
        if (checkParam(params, "verifyCode", et_verification_code_val.getText().toString(), "请输入短信验证码")) {
            return;
        }
        OkGo.<String>post(HostConstant.QUICK_AUTH_CONFIRM)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_QuickAuth(2, response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析鉴权申请接口返回的数据
     *
     * @param type     1.鉴权申请 2.鉴权确认
     * @param response
     */
    private void parseJson_QuickAuth(int type, String response) {
        QuickAuthApplyBean bean;
        try {
            bean = new Gson().fromJson(response, QuickAuthApplyBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            if (type == 1) {
                setVerificationCodeStatuts(true);
            }
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            if (type == 1) {
                setVerificationCodeStatuts(true);
            }
            return;
        }

        if (bean == null || bean.getData() == null || StringUtils.isNullOrEmpty(bean.getData().getAuthApplyNo())) {
            if (type == 1) {
                setVerificationCodeStatuts(true);
            }
            showConfirmAlert(this, "提示", getString(R.string.no_data));
            return;
        }
//        authApplyNo = bean.getData().getAuthApplyNo();
        switch (type) {
            case 1:
                setVerificationCodeStatuts(true);
                time.start();
                currentDataBean = bean.getData();
                sMobileNo = saveAddBankCardEvent.getMobilePhone();
                saveAddBankCardEvent.setTrustChannelId(trustChannelId);
                saveAddBankCardEvent.setAuthApplyNo(bean.getData().getAuthApplyNo());
                break;
            case 2:

                if (bankList == null) {
                    showConfirmAlert(mActivity, "请选择归属银行");
                    return;
                }
                saveAddBankCardEvent.setTrustChannelId(trustChannelId);
                QuickAuthApplyBean.DataBean authDataBean = bean.getData();
                saveAddBankCardEvent.setAuthApplyNo(authDataBean.getAuthApplyNo());
                Intent intent = null;
                if ("H5".equals(authDataBean.getAuthMethod())) {
                    intent = new Intent().setClass(mActivity, MerChantsBankActivity.class);
                    intent.putExtra("formContent", authDataBean.getFormContent());
                    intent.putExtra("returnUrl", authDataBean.getReturnUrl());
                    startActivityForResult(intent, HostConstant.START_CHANTS_BANK);
                } else {
                    addBankCardUpLoad();
                }
                break;
            default:
                break;
        }

    }

    /**
     * 银联插件报文获取
     *
     * @param bean
     */
    private void UpdateChinaPayAuth(QuickAuthApplyBean.DataBean bean) {
        Utils.setPackageName(getPackageName());
        String xml = ChinaPayUtils.getXml(ServiceConfig.CHINA_PAY_ENVIRONMENT, bean.getMerId(), bean.getMerOrderId(),
                bean.getMerOrderTime(), bean.getCharacterCode(), bean.getSign());

        // 调用银行插件进行开户，在此类的onResume()方法中获取插件的返回结果
        Intent inten = new Intent(this, Initialize.class);
        inten.putExtra(CPGlobaInfo.XML_TAG, xml);
        startActivity(inten);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(Utils.getPayResult())) {
            String str = Utils.getPayResult();
            MentorLogger.Log(TAG, "银联返回数据：  " + str);
            String respCode = str.substring(10, 14);
            if (respCode.equals("0000")) {
                //TODO 是否还有接口要调取
                quickAuthConfirm(saveAddBankCardEvent.getAuthApplyNo());
            } else {
                showConfirmAlert(mActivity, "银联认证失败");
            }
            ChinaPayUtils.printChinapayResultCodeInfo(respCode);
        }
        CPGlobaInfo.init(); // 清空返回结果

        if (!mentorApplication.needLogin() && !getFundCustomerNo().equals(currLoginFundCustomerNo)) {
            currLoginFundCustomerNo = getFundCustomerNo();
            tv_bank_reserve_phone_val.setText(mentorApplication.accountLoginBean.getData().getMobileNo());
            getBankList();
        }
    }


    private void setVerificationCodeStatuts(boolean isOpen) {
        if (isOpen) {
            if (tv_bank_reserve_phone_val.getText().toString().length() < 11) {
                btn_get_verification_code.setText("获取验证码");
                btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
                btn_get_verification_code.setClickable(false);
            } else {
                btn_get_verification_code.setText("获取验证码");
                btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_click_style);
                btn_get_verification_code.setClickable(true);
            }

        } else {
            btn_get_verification_code.setText("获取验证码");
            btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
            btn_get_verification_code.setClickable(false);

        }
    }

    /**
     * 根据输入的银行卡号 查询 卡相关信息  卡bin
     */
    private void queryCardBinByBankAccountNo() {
        Map<String, String> params = new HashMap<>();
        if (checkParam(params, "bankAccountNo", et_bank_card_no_val.getText().toString(), "请输入银行卡号")) {
            return;
        }
        params.put("customerNo", mentorApplication.userBean.getFundCustomerNo());
        OkGo.<String>post(HostConstant.QUERY_CARD_BIN_BY_BANK_ACCOUNT_NO)
                .tag(this)
                .upJson(new Gson().toJson(HttpUtils.getCommonParams(this, params)))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_CardBinInfo(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析鉴权申请接口返回的数据
     *
     * @param response
     */
    private void parseJson_CardBinInfo(String response) {
//        hideLoading();
        SmartCardBinByBankAccountNoBean bean;
        try {
            bean = new Gson().fromJson(response, SmartCardBinByBankAccountNoBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (bean == null
                || TextUtils.isEmpty(bean.getErrorCode())) {
            showToast(MentorConst.SERVER_BUSY_TIP);
            return;
        }
        BaseBean baseBean = new BaseBean();
        baseBean.setRespCode(bean.getErrorCode());
        baseBean.setRespMsg(bean.getErrorMessage());
        if (!CommonUtil.checkState(this, baseBean, response)) {
            return;
        }

        if (bean == null || bean.getData() == null || bean.getData().getCardBin() == null || StringUtils.isNullOrEmpty(bean.getData().getCardBin().getBankNo())) {
            showConfirmAlert(this, "提示", "暂不支持此卡");
            return;
        }
        //银行卡添加类型 planBuy：添加可定投的一行卡   否则为正常
        if ("planBuy".equals(addType)) {
            if (bean.getData().getCardBin() != null && !StringUtils.isNullOrEmpty(bean.getData().getCardBin().getBankNo())) {
                if (setSelectBankNoOrName(bean.getData().getCardBin().getBankNo())) {
                    return;
                }
            }
        } else {
            if (bean.getData().getSupportBankMap() == null || StringUtils.isNullOrEmpty(bean.getData().getSupportBankMap().getBankCode())) {

            } else {
                if (setSelectBankNoOrName(bean.getData().getSupportBankMap().getBankCode())) {
                    return;
                }
            }
        }
        showConfirmAlert(this, "提示", "暂不支持此卡");

    }

    private boolean setSelectBankNoOrName(String banNo) {

        for (QueryBankInfoListBean.DataBean beanBank : bankList) {
            if (beanBank.getBankCode().equals(banNo)) {
                bankName = beanBank.getBankName();
                tv_bank_card_name_val.setText(bankName);
                bankCode = beanBank.getBankCode();
                trustChannelId = beanBank.getTrustChannelId();
                return true;
            }
        }
        return false;
    }


}
